<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './data';
  import { addProductApi, modProductApi } from '/@/api/admin/goods';

  export default defineComponent({
    name: 'AccountModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const rowId = ref('');

      const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          rowId.value = data.record.id;
          setFieldsValue({
            ...data.record,
          });
        }

        updateSchema([
          {
            field: 'pwd',
            show: !unref(isUpdate),
          },
          {
            field: 'dept',
            componentProps: {},
          },
        ]);
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增物资' : '编辑物资资料'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          // TODO custom api
          console.log(values);
          // 如果id存在
          if (values.id) {
            // 则请求修改接口
            await modProductApi(values);
          } else {
            [
              { id: 1, name: '主食' },
              { id: 2, name: '零食' },
              { id: 3, name: '母婴用品' },
              { id: 4, name: '女性用品' },
              { id: 5, name: '酒水饮料' },
              { id: 6, name: '日用品' },
              { id: 7, name: '团购平台' },
              { id: 8, name: '超市' },
              { id: 9, name: '药品保健' },
              { id: 11, name: '团餐配送' },
              { id: 12, name: '加油站' },
              { id: 13, name: '宠物' },
            ].map((item) => {
              if ((item.id = values.productCategoryId)) {
                values.productCategory = item.name;
              }
            });

            const deliverArea = [] as string[];
            for (let index = 0; index < values.deliverArea.length; index++) {
              const deliverId = values.deliverArea[index] as number;
              [
                { id: 0, name: '全市' },
                { id: 1, name: '黄浦' },
                { id: 2, name: '徐汇' },
                { id: 3, name: '长宁' },
                { id: 4, name: '静安' },
                { id: 5, name: '普陀' },
                { id: 6, name: '虹口' },
                { id: 7, name: '杨浦' },
                { id: 8, name: '闵行' },
                { id: 9, name: '宝山' },
                { id: 10, name: '嘉定' },
                { id: 11, name: '浦东' },
                { id: 12, name: '金山' },
                { id: 13, name: '松江' },
                { id: 14, name: '青浦' },
                { id: 15, name: '奉贤' },
                { id: 16, name: '崇明' },
              ].map((item) => {
                if (item.id == deliverId) {
                  deliverArea.push(item.name);
                }
              });
            }
            values.deliverArea = deliverArea.join(',');
            // 否则请求创建接口
            await addProductApi([values]);
          }
          closeModal();
          emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit };
    },
  });
</script>
